<?php
namespace App\Http\Controllers\Api\v1;

use App\Http\Controllers\Api\BaseController;
use App\Http\Requests\UserRequest;
use App\Repositories\UserRepository;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;
use Illuminate\Http\Request;

class LoginController extends BaseController {

	protected $model;

	public function __construct(UserRepository $user) {
		parent::__construct();
		$this->model = $user;
	}

	public function register(UserRequest $request) {
		$user = $this->model->create($request->all());
		$request->account = $request->name;
		$token = $this->login($request, 'register');
		return $this->response->withSuccess(compact('user', 'token'));
	}

	public function login(Request $request, $type = 'login') {
		$this->validate($request, [
			'account' => 'required',
			'password' => 'required',
		]);

		$client_secret = env('CLIENT_SECRET2') ?: abort(500, 'CLIENT_SECRET2 Not configured in .env');

		$http = new Client;
		try {
			$response = $http->post(url()->previous() . '/oauth/token', [
				'form_params' => [
					'grant_type' => 'password',
					'client_id' => '2',
					'client_secret' => $client_secret,
					'username' => $request->account,
					'password' => $request->password,
					'scope' => '',
				],
			]);
			$token = json_decode((string) $response->getBody()->getContents(), true);
			if ($type === 'login') {
				$user = $this->model->getUserByAccount($request->account);
				return $this->response->withSuccess(compact('user', 'token'));
			} else {
				return $token;
			}
		} catch (ClientException $e) {
			$statusCode = $e->getCode();
			if ($e->hasResponse()) {
				$body = (string) $e->getResponse()->getBody()->getContents();
			} else {
				$body = json_encode(['error' => 'System Error', 'message' => 'Something went wrong. Please try again']);
			}
			abort($statusCode, $body);
		} catch (ServerException $e) {
			$body = json_encode(['error' => 'Fatal Error', 'message' => 'Server Died.Please Contact the webmaster']);
			abort(500, $body);
		}
	}

	public function refresh(Request $request) {
		$this->validate($request, [
			'refresh_token' => 'required',
		]);
		$http = new Client;
		try {
			$response = $http->post(url()->previous() . '/oauth/token', [
				'form_params' => [
					'grant_type' => 'refresh_token',
					'refresh_token' => $request->refresh_token,
					'client_id' => '2',
					'client_secret' => env('CLIENT_SECRET2'),
					'scope' => '',
				],
			]);
			$token = json_decode((string) $response->getBody()->getContents(), true);
			return $this->response->withSuccess(compact('token'));
		} catch (ClientException $e) {
			$statusCode = $e->getCode();
			if ($e->hasResponse()) {
				$body = (string) $e->getResponse()->getBody()->getContents();
			} else {
				$body = json_encode(['error' => 'System Error', 'message' => 'Something went wrong. Please try again']);
			}
			abort($statusCode, $body);
		} catch (ServerException $e) {
			$body = json_encode(['error' => 'Fatal Error', 'message' => 'Server Died.Please Contact the webmaster']);
			abort(500, $body);
		}
	}
}
